package cn.com.wxd.action.user;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import cn.com.wxd.dao.frame.AttachDao;
import cn.com.wxd.service.attach.entity.AttachInfo;
import cn.com.wxd.service.attach.AttachConfEntity;
import cn.com.wxd.service.attach.AttachUtil;
import cn.com.wxd.common.CharUtil;
import cn.com.wxd.common.DateUtil;
import cn.com.wxd.common.JsonUtil;
import cn.com.wxd.common.file.ImageUtil;
import cn.com.wxd.common.file.MyFileUtil;

/**
 * Title:用户头像上传
 * Description:cn.com.wxd.servlet
 * <p>
 * Company: wxd网站系统
 * Copyright: Copyright (c) 2015
 * All right reserved.
 * Created by ComXu on 2017/5/10.
 *
 * @author WangXuDong
 * @version 1.0
 */
@Controller
@RequestMapping("/user")
public class UserPicUploadCtl {

    private static final Logger log = LoggerFactory.getLogger(UserPicUploadCtl.class);
    @Resource
    private AttachDao attachDao;

    @RequestMapping("/picupload")
    public void userPicUpload(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        String picX = "";  //图片裁剪的起点X
        String picY = "";    //图片裁剪的起点Y
        String picWidth = ""; //图片裁剪宽度
        String picHight = ""; //图片裁剪高度
        String LastheadImg = ""; //裁剪的图片地址
        String isCutImg = "";//是否进行裁剪裁剪
        AttachConfEntity ace = null;
        List<AttachInfo> fileInfoList = new ArrayList<>();
        try {
            ace = AttachUtil.instance().getAttachConfByParamName("userheadpic");
        } catch (Exception e) {
            log.info("头像上传配置文件参数：userheadpic配置错误" + e.getMessage(), e);
        }
        String savePath = null;
        if (ace != null) {
            savePath = ace.getPath() + File.separator + DateUtil.getDatetimeStr("yyyyMMdd") + File.separator;
        }
        try {
            File dirfile = new File(savePath);
            if (!dirfile.exists()) {
                dirfile.mkdirs();
            }
        } catch (Exception e) {
            log.info("头像报错文件夹无法初始化或无法读取!" + e.getMessage(), e);
            return;
        }
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                //FileItem item = (FileItem) iter.next();
                //                if (item.isFormField()) {
                //一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if (file != null) {
                    AttachInfo fue = new AttachInfo();  //new一个文件信息对象
                    String fileName = file.getName();
                    String extName = fileName.substring(fileName.lastIndexOf(".") + 1);
                    if (isImgFile(extName) == true) {
                        fue.setFileName(fileName);
                        fue.setSize(String.valueOf(file.getSize()));
                        fue.setPath(savePath);
                        if (fileName != null) {
                            String endstr = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                            fue.setExtName(endstr);
                            fileName = DateUtil.getTimestamp() + CharUtil.getRanNumber(4) + endstr;
                        }
                        //设置文件访问路径。。此路径并非正真的访问路径，但是这里返回一个正常访问的地址
                        fue.setAccessPath(request.getContextPath() + "/Stream/" + ace.getParamname() + "/" + fileName);
                        fue.setUpFileName(fileName);
                        File uploadedFile = new File(savePath, fileName);
                        try {
                            //上传
                            file.transferTo(uploadedFile);
                            if (ace.isRecorddb()) {
                                try {
                                    String fileid = DateUtil.getTimestamp() + CharUtil.getRanNumber(2);
                                    fue.setFileId(fileid);
                                    attachDao.insertAttachInfo(fue);
                                } catch (Exception e) {
                                    log.error("文件上传信息存入数据库失败!", e);
                                }
                            }
                            fileInfoList.add(fue);
                        } catch (Exception e) {
                            log.info("文件上传出现问题：" + e.getMessage());
                        }
                    }

                }
            }
        } else {
            picX = request.getParameter("picX");
            picY = request.getParameter("picY");
            picWidth = request.getParameter("picWidth");
            picHight = request.getParameter("picHeight");
            LastheadImg = request.getParameter("LastheadImg");
            isCutImg = request.getParameter("isCutImg");
        }
        if (CharUtil.stringParsInt(picWidth) < 0) {
            picWidth = "100";
        }
        if (CharUtil.stringParsInt(picHight) < 0) {
            picHight = "100";
        }
        if (CharUtil.stringParsInt(picX) < 0) {
            picX = "0";
        }
        if (CharUtil.stringParsInt(picY) < 0) {
            picY = "0";
        }
        if (isCutImg != null && isCutImg.equalsIgnoreCase("true")) { //容许裁剪图片
            //裁剪指定路劲的图片
            // 返回修改的图片文件信息
            if (LastheadImg != null && !LastheadImg.trim().equals("")) {
                try {
                    //修改的文件的信息
                    AttachInfo fue = new AttachInfo();
                    String[] param = LastheadImg.split("\2");
                    fue.setUpFileName(param[1]);
                    fue.setExtName(param[1].substring(param[1].lastIndexOf(".") + 1));
                    fue.setPath(param[0]);
                    fileInfoList = new ArrayList<>();
                    if (isImgFile(fue.getExtName())) {
                        //裁剪图片
                        ImageUtil iu = new ImageUtil(fue.getPath() + File.separator + fue.getUpFileName());
                        //生成新的文件和文件名
                        String outPath = ace.getPath() + File.separator + DateUtil.getDatetimeStr("yyyyMMdd")
                                + File.separator;
                        String newUpfileName =
                                DateUtil.getTimestamp() + CharUtil.getRanNumber(4) + "." + fue.getExtName();
                        iu.cutImage(outPath + newUpfileName, CharUtil.stringParsInt(picX), CharUtil.stringParsInt(picY),
                                CharUtil.stringParsInt(picWidth), CharUtil.stringParsInt(picHight)
                        );//裁剪后替换原来的图片
                        //删除之前的图片
                        MyFileUtil.deleteFile(new File(fue.getPath() + File.separator + fue.getUpFileName()));
                        //重新放入新的信息
                        fue.setPath(outPath);
                        fue.setUpFileName(newUpfileName);
                        fue.setAccessPath(
                                request.getContextPath() + "/Stream/" + ace.getParamname() + "/" + newUpfileName);
                        fileInfoList.add(fue);
                    }
                } catch (IOException e) {
                    log.error("图片裁剪出现问题" + e.getMessage());
                }
            }
            String json = JsonUtil.objectToJson(fileInfoList);
            if (out != null) {
                out.print(json);
                out.flush();
                out.close();
            }
        }
    }

    private boolean isImgFile(String extName) {
        if (extName == null) {
            return false;
        }
        if (extName.lastIndexOf(".") >= 0) {
            extName = extName.substring(extName.lastIndexOf(".") + 1);
        }
        if (extName.equalsIgnoreCase("png") || extName.equalsIgnoreCase("jpeg") || extName.equalsIgnoreCase("bmp")
                || extName.equalsIgnoreCase("gif") || extName.equalsIgnoreCase("jpg")) {
            return true;
        }
        return false;
    }
}
